package vn.lumi.smarthome.network;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Calendar;

import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.TBL_DeviceScene;
import vn.lumi.smarthome.io.database.TBL_DeviceState;
import vn.lumi.smarthome.io.database.TBL_Scene;
import vn.lumi.smarthome.io.database.TBL_Schedule;
import vn.lumi.smarthome.io.model.Device;
import vn.lumi.smarthome.io.model.Scene;
import vn.lumi.smarthome.io.model.Schedule;
import vn.lumi.smarthome.io.model.Time;
import vn.lumi.smarthome.ulti.Preference;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Parcel;
import android.util.Log;

public class CreateSchedule extends AppMsg {

	// attributes
	private int Schedule_id = 0;
	private int ScheduleState = 0;
	private int Device_id = 0;
	private boolean Repeat = false;
	private boolean[] Day = new boolean[7]; // 7 days of a week Day[0] -->
											// Monday
	private Time StartTime = new Time(); // [0] = hour, [1] =minute
	private Time EndTime = new Time();
	private int Duration;
	private int[] DeviceState = null;
	private int newConfigVersion = 0;

	// private boolean isNow;

	public CreateSchedule(int Msg_id, int uid, int sid, int schedule_id,
			int scheduleState, int dev_id, boolean repeat, boolean[] days,
			Time start_time, Time end_time, int[] dev_state) {
		super(NetMessage.CMD_APP_CREATE_SCHEDULE, Msg_id, uid, sid);
		Device_id = dev_id;
		Schedule_id = schedule_id;
		this.ScheduleState = scheduleState;
		Repeat = repeat;
		Day = days;
		StartTime = start_time;
		EndTime = end_time;
		DeviceState = new int[dev_state.length];
		for (int i = 0; i < dev_state.length; i++) {
			DeviceState[i] = dev_state[i];
		}
		// this.isNow = isNow;
		// TODO Auto-generated constructor stub
	}

	@Override
	public byte[] generateByteArray() {
		byte[] result = new byte[12 + DeviceState.length];
		result[0] = (byte) this.Cmd_id;
		result[1] = (byte) this.Msg_id;
		result[2] = (byte) this.user_id;
		result[3] = (byte) this.session_id;
		result[4] = (byte) this.Schedule_id;
		result[5] = (byte) this.ScheduleState;
		result[6] = (byte) Device_id;
		// days
		for (int i = 0; i < 7; i++) {
			if (Day[i] == true)
				result[7] |= (1 << (6 - i));
			else
				result[7] &= ~(1 << (6 - i));
		}
		if (Repeat == true)
			result[7] |= (1 << 7);
		else
			result[7] &= ~(1 << 7);

		result[8] = (byte) StartTime.getHour();
		result[9] = (byte) StartTime.getMinute();

		result[10] = (byte) EndTime.getHour();
		result[11] = (byte) EndTime.getMinute();
		int stateLength = DeviceState.length;
		for (int i = 0; i < stateLength; i++) {
			result[12 + i] = (byte) DeviceState[i];
		}
		Log.e("ban tin", "CreatSchedule" + Arrays.toString(result));
		return result;
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub
		dest.writeInt(this.Schedule_id);
		dest.writeInt(this.ScheduleState);
		dest.writeInt(this.Device_id);
		dest.writeBooleanArray(new boolean[] { this.Repeat });
		dest.writeBooleanArray(this.Day);
		dest.writeInt(this.StartTime.getHour());
		dest.writeInt(this.StartTime.getMinute());
		dest.writeInt(this.EndTime.getHour());
		dest.writeInt(this.EndTime.getMinute());
		dest.writeIntArray(this.DeviceState);
	}

	@Override
	public void doIfSendSuccessful(Context context) {
		// TODO Auto-generated method stub

		if (Schedule_id == 255) {
			// Thong bao la qua nhieu lich, phai xoa bot lich di
			// inform UI
			Intent intent = new Intent();
			intent.setAction(context
					.getString(R.string.txt_broadcast_create_schedule_overload));
			context.sendBroadcast(intent);
		} else {
			// insert device state
			ContentValues contentValues = new ContentValues();
			contentValues.put(TBL_DeviceState.VALUE, this.DeviceState[0]);
			contentValues.put(TBL_DeviceState.BLIND_STATE,
					Device.DEVICE_STATE_BLIND_STATE_STOPPED);
			Log.e("ban tin", "" + TBL_DeviceState.CONTENT_URI_DEVICE_STATE);
			Uri uri2 = context.getContentResolver().insert(
					TBL_DeviceState.CONTENT_URI_DEVICE_STATE, contentValues);
			int state_id = Integer.parseInt(uri2.getLastPathSegment());

			// save schedule into database
			ContentValues values = new ContentValues();
			values.put(TBL_Schedule._ID, this.Schedule_id);
			values.put(TBL_Schedule.DEVICE_ID, this.Device_id);
			// values.put(TBL_Schedule.DURATION, this.Duration);

			// Luu thoi gian bat
			int turnOnHour, turnOnMinute, turnOffHour, turnOffMinute;
			if(this.StartTime.getHour() == Schedule.SCHEDULE_NOT_TURNON_TYPE)
			{
				turnOnHour = this.StartTime.getHour();
			}
			// kiem tra xem co phai bat thiet bi bjo ko, neu co thi bo bit 1 o byte hour di
			else if(this.StartTime.getHour() > 24)
			turnOnHour = (this.StartTime.getHour() & 127);
			else  {
				turnOnHour = this.StartTime.getHour();
			}
			turnOnMinute = this.StartTime.getMinute();
			values.put(TBL_Schedule.HOUR, turnOnHour);
			values.put(TBL_Schedule.MINUTE, turnOnMinute);

			// luu thoi gian tat
			turnOffHour = this.EndTime.getHour();
			turnOffMinute = this.EndTime.getMinute();
			values.put(TBL_Schedule.HOUR_END, turnOffHour);
			values.put(TBL_Schedule.MINUTE_END, turnOffMinute);

			int RepeatInt = 0;
			if (this.Repeat == true)
				RepeatInt = Schedule.SCHEDULE_DAY_ON;
			else
				RepeatInt = Schedule.SCHEDULE_DAY_OFF;
			values.put(TBL_Schedule.REPEAT, RepeatInt);

			int[] DaysInt = new int[7];
			for (int i = 0; i < 7; i++) {
				if (this.Day[i] == true)
					DaysInt[i] = Schedule.SCHEDULE_DAY_ON;
				else
					DaysInt[i] = Schedule.SCHEDULE_DAY_OFF;
			}
			values.put(TBL_Schedule.MONDAY, DaysInt[0]);
			values.put(TBL_Schedule.TUESDAY, DaysInt[1]);
			values.put(TBL_Schedule.WEDNESDAY, DaysInt[2]);
			values.put(TBL_Schedule.THURSDAY, DaysInt[3]);
			values.put(TBL_Schedule.FRIDAY, DaysInt[4]);
			values.put(TBL_Schedule.SATURDAY, DaysInt[5]);
			values.put(TBL_Schedule.SUNDAY, DaysInt[6]);

			values.put(TBL_Schedule.STATE, this.ScheduleState);
			values.put(TBL_Schedule.STATE_ID, state_id);
			context.getContentResolver().insert(
					TBL_Schedule.CONTENT_URI_SCHEDULE, values);

			// save config in preferences
			LumiHome.HC_Config_ver = this.newConfigVersion;
			Preference.saveConfigVersion(context, this.newConfigVersion);

			// inform UI
			Intent intent = new Intent();
			intent.setAction(context
					.getString(R.string.txt_broadcast_create_schedule_successful));
			context.sendBroadcast(intent);
		}
	}

	@Override
	public void doIfSendFail(Context context) {
		// TODO Auto-generated method stub
		// inform UI
		Intent intent = new Intent();
		intent.setAction(context
				.getString(R.string.txt_broadcast_create_schedule_failed));
		context.sendBroadcast(intent);
	}

	@Override
	public void readFromParcel(Parcel in) {
		// TODO Auto-generated method stub
		this.Schedule_id = in.readInt();
		this.ScheduleState = in.readInt();
		this.Device_id = in.readInt();
		boolean[] temp = new boolean[1];
		in.readBooleanArray(temp);
		this.Repeat = temp[0];
		in.readBooleanArray(this.Day);
		this.StartTime = new Time(in.readInt(), in.readInt());
		this.EndTime = new Time(in.readInt(), in.readInt());
		// this.Duration = in.readInt();
		in.readIntArray(DeviceState);
	}

	@Override
	public boolean isCorrectReply(byte[] input, int length) {
		// TODO Auto-generated method stub
		boolean result = false;
		AckSchedule ack = new AckSchedule();
		if (ack.isCorrectFormat(input, length)) {
			Log.e("ban tin", "CreateSchedule success0");
			ack.parseMessage(input, length);
			Log.e("ban tin", "ackCreatSchedule" + ack.getMsg_id());
			Log.e("ban tin", "MsgId_creatSchedule" + this.Msg_id);
			if (ack.getMsg_id() == this.Msg_id
					&& ack.getUserId() == this.getUid()) {
				this.Schedule_id = ack.getScheduleId();
				Log.e("ban tin", "Schedule_id" + Schedule_id);
				this.newConfigVersion = ack.getConfigVersion();

				result = true;
			}
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see vn.lumi.smarthome.network.AppMsg#isCorrectBusy(byte[], int)
	 */
	@Override
	public boolean isCorrectBusy(byte[] input, int length) {
		// TODO Auto-generated method stub
		boolean result = false;
		HC_ACK_BUSY ack_busy = new HC_ACK_BUSY();
		if (ack_busy.isCorrectFormatBusy(input, length)) {
			ack_busy.parseMessage(input, length);
			if (ack_busy.getMsg_id() == this.Msg_id)
				result = true;
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see vn.lumi.smarthome.network.AppMsg#doIfHcBusying()
	 */
	@Override
	public void doIfHcBusying() {
		// TODO Auto-generated method stub

	}

}
